#!/usr/bin/env ruby 
require 'optparse'
require 'tmpdir'


reg_args = /^-js|-swf|-swf9|-as3|-php|-cpp|-swf-version|-swf-header|-swf-lib|--flash-strict|--flash-use-stage|--gen-hx-classes|--php-front|-debug|-x|-neko/

help = "Snhaxe scripting frontend to HaXe Compiler 1.0 - (c) Justin Donaldson
 Usage : snhaxe.rb  <class names...>
 Options :
  -cp <path> : add a directory to find source files
  -xml <file> : generate XML types description
  -main <class> : select startup class
  -lib <library[:version]> : use an haxelib library
  -D <var> : define a conditional compilation flag
  -v : turn on verbose mode
  -debug : add debug informations to the compiled code
  -x <file> : shortcut for compiling and executing a neko file
  -resource <file>[@name] : add a named resource file
  -exclude <filename> : don't generate code for classes listed in this file
  -prompt : prompt on error
  -cmd : run the specified command after successful compilation
  -cache: if the script has already been compiled, skip compilation and rerun the bytecode
  --no-traces : don't compile trace calls in the program
  --neko-source : keep generated neko source
  --next : separate several haxe compilations
  --display : display code tips
  --no-output : compiles but does not generate any file
  --times : mesure compilation times
  --no-inline : disable inlining
  --no-opt : disable code optimizations
  --remap <package:target> : remap a package to another one
  -help  Display this list of options
  --help  Display this list of options\n"
cache = false
i=0
main = ""
file_name = ""

ARGV.each do |a|
  if (a.scan(reg_args) != [])
    raise "Snhaxe does not allow this argument: "+ a
  elsif (a == "-main")
    main = ARGV[i+1]
    ARGV[i] =  ""
    ARGV[i+1] = ""
  elsif (a == "-help" || a == "--help")
     print help
     Process.exit
  elsif (a == "-cache")
    cache = true
    ARGV[i] = ""
  elsif (a.match(/\.\/\w+/)) # file input argument
    file_name = a
    ARGV[i] = ""
    
  end
  i+=1
end


if (file_name == nil || file_name == '')
  raise "No input for snhaxe..."
end

begin
  script_string = File.read(file_name)
rescue Errno::ENOENT
  raise "File content was not provided by "+ file_name
end

# If main class is not specified, find the first class with a main function.
if (main == nil || main == "")
  main_class_g = /class\s+(\w+)[^(class)]*public\s+static\s+function\s+main/m
  if (script_string.scan(main_class_g) == [])
    raise "Couldn't find valid main class"
  else
    main = script_string.scan(main_class_g)[0].to_s
  end
end

# set up the script string as an array of lines
script_file = script_string.split("\n")
# shift off the first one (with the shebang)
script_file.shift


tmpd = Dir.tmpdir
# Dir.pwd.gsub("\/","_")
tempfilename = File.join(tmpd, 'snhaxe', Dir.pwd, main+'.hx')


if (File.exist?(tempfilename+'.n') && File.mtime(file_name) < File.mtime(tempfilename) && cache)
  print `neko #{tempfilename}.n`
else
  `mkdir -p #{File.join(tmpd,'snhaxe', Dir.pwd)}`
  tempfile = File.new(tempfilename, "w")
  tempfile.syswrite(script_file.join("\n"))
  tempfile.close
  print `haxe -cp #{tmpd} #{ARGV.join(" ")} -main #{main} -x #{tempfilename}`
end

__END__

Copyright 2009 Justin Donaldson

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.


